var express = require('express');
var router = express.Router();
var {save_post, get_article, get_hot_list} = require('../db/post');

router.get('/', function(req, res, next) {
  res.render('list_posts', { title: '博文列表' });
});

router.get('/new', function(req, res, next) {
  res.render('new_post', { title: '添加博文' });
});

router.post('/save', async function(req, res, next) {
  //获取请求中的表单数据，四个参数分别是:title, author, date, content.
  let article = {
    title: req.body.title,
    author: req.body.author,
    date: req.body.date,
    content: req.body.content,
    tags: req.body.tags
  };
  let slug = await save_post(article)
  if (slug) {
    res.redirect(`./view/${slug}`);
  } else {
    res.render('save', { title: '保存失败' });
  }
})

router.get('/view/:slug', async function(req, res, next) {
  let slug = req.params.slug;
  let article = await get_article(slug);
  res.render('article', {article});
});

router.get('/edit/:slug', async function(req, res, next) {
  let slug = req.params.slug;
  let article = await get_article(slug);
  res.render('edit', {article});
});

router.get('/hotlist', async function(req, res, next) {
  let hot_list = await get_hot_list();
  res.send(hot_list);
});

module.exports = router;
